package com.tuniu.agents.tools.trip;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.tuniu.agents.message.ToolLoggerInfo;
import com.tuniu.agents.tool.EnvParam;
import com.tuniu.agents.tool.EnvRequest;
import com.tuniu.agents.util.HttpManager;
import com.tuniu.agents.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

public class TripExtractorTool implements BiFunction<TripExtractorTool.Request, ToolContext, TripExtractorTool.Response> {

    private static final Logger logger = LoggerFactory.getLogger(TripExtractorTool.class);

    public static final String TOOLNAME = "trip_extractor";

    private final String tripExtractorUrl;
    private final String accessKey;

    @Autowired
    private HttpManager httpManager;

    public TripExtractorTool(TripProperties properties) {
        this.tripExtractorUrl = properties.getTripExtractorUrl();
        this.accessKey = properties.getAccessKey();
    }

    @ToolLoggerInfo
    @Override
    public Response apply(@EnvRequest Request request, ToolContext toolContext) {

        try {
            Response response = httpManager.post(tripExtractorUrl, request, Response.class, Map.of(accessKey,accessKey));
            if(!response.successCode() || CollectionUtils.isEmpty(response.data())){
                logger.warn("TripExtractorTool apply fail or empty request:{}", JsonUtil.toJson(request));
                return null;
            }
            return response;
        }catch (Exception e){
            logger.warn("TripExtractorTool apply error request:{}", JsonUtil.toJson(request),e);
            return null;
        }

    }

    @JsonClassDescription("获取行程信息")
    public record Request(
            @EnvParam("trip_info")
            @JsonProperty(value = "trip_info") @JsonPropertyDescription("行程信息")
            String tripInfo)
    { }

    @JsonClassDescription("行程数据的返回")
    public record Response(
            @JsonProperty(value = "successCode") @JsonPropertyDescription("成功标识") boolean successCode,
            @JsonProperty(value = "data") @JsonPropertyDescription("车次信息") List<String> data) {
    }

}
